package com.nanjing.east.cloud.web;

import com.nanjing.east.cloud.PayOrderDTO;
import com.nanjing.east.cloud.alipay.AlipayClient;
import com.nanjing.east.cloud.form.PayForm;
import com.nanjing.east.cloud.service.HardwareService;
import com.nanjing.east.cloud.service.OrderService;
import com.nanjing.east.cloud.vo.PayOrder2VO;
import com.nanjing.east.cloud.vo.PayOrderVO;
import com.nanjing.east.cloud.vo.ResponseVO;
import com.nanjing.east.cloud.wechatpay.WechatPayClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Author: XIECHAO260
 * @Desc:
 * @Date: 2018/11/26 15:39
 * @Modified By:
 * @Project PAY-GATEWAY
 */
@Controller
@Slf4j
public class PayController {

    @Autowired
    private WechatPayClient wechatPayClient;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private HardwareService hardwareService;

    @RequestMapping("/")
    @ResponseBody
    String home() {

        log.info("payContoller.home");
        return "Hello World!";
    }


    @RequestMapping(value="/createOrder",method= RequestMethod.GET)
    @ResponseBody
    ResponseVO<PayOrderVO> createOrder(@RequestBody PayForm payForm) {
        log.info("PayController.createOrder:{}", payForm);
        ResponseVO<PayOrderVO> responseVO = new ResponseVO();
        try {
            String payOrderNo = getOrderNo();
            PayOrderDTO payOrderDTO = PayOrderDTO.builder()
                    .storeId(payForm.getStoreId())
                    .cabinetId(payForm.getCabinetId())
                    .lockId(payForm.getLockId())
                    .payAmount(payForm.getPayAmount())
                    .payOrderNo(payOrderNo)
                    .build();
            String qrCode;
            if (StringUtils.equals("2", payForm.getPayType())) {
                qrCode = alipayClient.preCreateOrder(payOrderDTO);
            } else {
                qrCode = wechatPayClient.preCreateOrder(payOrderDTO);
            }
            PayOrderVO payOrderVO = PayOrderVO.builder()
                    .payOrderNo(payOrderNo)
                    .storeId(payForm.getStoreId())
                    .cabinetId(payForm.getCabinetId())
                    .lockId(payForm.getLockId())
                    .payAmount(payForm.getPayAmount())
                    .qrCode(qrCode)
                    .build();
            if (StringUtils.isNotBlank(qrCode)) {
                responseVO.setErrorCode("1");
                responseVO.setMessage("success");
                responseVO.setData(payOrderVO);
            } else {
                responseVO.setMessage("create order fail");
            }
        } catch (Exception e) {
            responseVO.setMessage("create order error");
            log.error("createOrder error:{}", e);
        }
        return responseVO;

    }

    @RequestMapping("/createOrder/{payType}")
    @ResponseBody
    ResponseVO<String> createOrder1(@PathVariable("payType") String payType) {
        PayForm payForm = new PayForm();
        payForm.setPayAmount("1");
        payForm.setPayType(payType);
        payForm.setStoreId("10001");
        payForm.setCabinetId("102");
        payForm.setLockId("01");
        log.info("PayController.createOrder:{}", payForm);
        ResponseVO<String> responseVO = new ResponseVO();
        String payOrderNo = getOrderNo();
        try {
            PayOrderDTO payOrderDTO = PayOrderDTO.builder()
                    .storeId(payForm.getStoreId())
                    .cabinetId(payForm.getCabinetId())
                    .lockId(payForm.getLockId())
                    .payAmount(payForm.getPayAmount())
                    .payOrderNo(payOrderNo)
                    .build();
            String qrCode;
            if (StringUtils.equals("2", payForm.getPayType())) {
                qrCode = alipayClient.preCreateOrder(payOrderDTO);
            } else {
                qrCode = wechatPayClient.preCreateOrder(payOrderDTO);
            }

            if (StringUtils.isNotBlank(qrCode)) {
                responseVO.setErrorCode("1");
                responseVO.setMessage("success");
                responseVO.setData(qrCode);
            } else {
                responseVO.setMessage("create order fail");
            }
        } catch (Exception e) {
            responseVO.setMessage("create order error");
            log.error("createOrder error:{}", e);
        }
        return responseVO;

    }

    @RequestMapping("/queryOrder/{storeId}")
    @ResponseBody
    ResponseVO<List<PayOrder2VO>> queryOrder(@PathVariable("storeId") String storeId) {
        ResponseVO<List<PayOrder2VO>> responseVO = new ResponseVO();
        List<PayOrder2VO> payOrderVOS = new ArrayList<>();
        log.info("订单查询门店编号:{}", storeId);
        try {
            payOrderVOS = orderService.queryOkOrder(60, storeId);
            responseVO.setErrorCode("1");
            responseVO.setMessage("success");
            responseVO.setData(payOrderVOS);
        } catch (Exception e) {
            responseVO.setMessage("query order error");
            log.error("queryOrder error:{}", e);
        }
        log.info("定时查询订单返回信息：{}", responseVO);
        return responseVO;

    }


    @RequestMapping("/callBack/{payOrderNo}")
    @ResponseBody
    ResponseVO<String> callBack(@PathVariable("payOrderNo") String payOrderNo) {
        ResponseVO<String> responseVO = new ResponseVO();
        log.info("回调支付订单号为:{}", payOrderNo);
        try {
            hardwareService.updateHardWareByNo(payOrderNo);
            responseVO.setErrorCode("1");
            responseVO.setMessage("success");
            responseVO.setData(payOrderNo);
        } catch (Exception e) {
            responseVO.setMessage("callBack error");
            log.error("callBack error:{}", e);
        }
        return responseVO;

    }


    public static String getOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if (hashCodeV < 0) {//有可能是负数
            hashCodeV = -hashCodeV;
        }
        return newDate + String.format("%015d", hashCodeV);
    }
}
